




#include "stdafx.h"
#include "NMessageMgr.h"
#include "NInter.h"
#include "NSyncObject.h"

NMessageMgr* NMessageMgr::m_cpSelf = NULL;

NMessageMgr::NMessageMgr()
{
	m_bOK = false;
	::InitializeCriticalSection(&m_CS);
	m_bOK = true;
}

NMessageMgr::~NMessageMgr()
{
	::DeleteCriticalSection(&m_CS);
}


bool NMessageMgr::CreateInstance(void)
{
	assert(NULL == m_cpSelf);
	m_cpSelf = new(nothrow) NMessageMgr();
	if(NULL == m_cpSelf) return false;
	if(false == m_cpSelf->isOK()){ delete m_cpSelf; m_cpSelf=NULL; return false; }
	return true;
}

void NMessageMgr::DestoryInstance(void)
{
	assert(NULL != m_cpSelf);
	if(NULL != m_cpSelf){ delete m_cpSelf; m_cpSelf=NULL; }
}


bool NMessageMgr::Insert(const unsigned int in_hID,NInter* in_cpInter)
{
	NSyncObject sync(m_CS);
	pair<OBJCONTAINER::iterator,bool> ret = m_ObjContainer.insert(make_pair(in_hID,in_cpInter));
	return ret.second;
}

void NMessageMgr::Remove(const unsigned int in_hID,NInter* in_cpInter)
{
	NSyncObject sync(m_CS);

	OBJCONTAINER::const_iterator iter = m_ObjContainer.find(in_hID);
	if(iter == m_ObjContainer.end()) return;
	assert(iter->second == in_cpInter);
	if(iter->second != in_cpInter) return;
	m_ObjContainer.erase(iter);
}


bool NMessageMgr::Post(
	const unsigned int in_ToInter,
	const unsigned int in_Msg,
	const unsigned int in_wParam,
	const unsigned int in_lParam)
{
	NSyncObject sync(m_CS);

	OBJCONTAINER::const_iterator iter = m_ObjContainer.find(in_ToInter);
	if(iter == m_ObjContainer.end()) return false;	
	NInter* cpInter = iter->second;
	cpInter->Receive(in_Msg,in_wParam,in_lParam);
	return true;
}

